//
//  FootprintView.m
//  cocoapodText
//
//  Created by apple on 16/9/15.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "ShiPei.h"
#import "FootprintView.h"
#import <Foundation/Foundation.h>

@interface FootprintView()<UITableViewDelegate,UITableViewDataSource,ChartViewDelegate,FSMyUIDatePickerDelegate>
@property(nonatomic,strong)NSMutableArray *conditionInfos;
@property(nonatomic,strong)NSMutableArray *queryDataInfos;
@end

@implementation FootprintView

/**
 *  初始化视图属性
 *
 *  @param frame 视图frame
 *
 *  @return self
 */
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        //定制View
        self.backgroundColor = [UIColor clearColor];
        self.userInteractionEnabled = YES; //设置为NO后，不再响应touch方法
        self.multipleTouchEnabled = YES;
        //控制子视图不能超出父视图的范围
        self.clipsToBounds = YES;
        //添加子视图
        [self subView];
    }
    return self;
}

//子视图懒加载
-(void)subView{
    //内容栏
    _AllBackView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, [ShiPei CGFloatMakeScale:TabChildContentW+10], kScreenH-CommonBarH-kStatusH-[ShiPei CGFloatMakeScale:FSCommonBottomH])];
    [self addSubview:_AllBackView];
    
    _pickerOverlay=[[UIView alloc]initWithFrame:CGRectMake(0, 0, [ShiPei CGFloatMakeScale:TabChildContentW+10], kScreenH-CommonBarH-kStatusH)];
    [_pickerOverlay setBackgroundColor:[[UIColor blackColor] colorWithAlphaComponent:0.17]];
    UITapGestureRecognizer *gestureRecognizer;
    gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                action:@selector(overlaycancel)];
    [_pickerOverlay addGestureRecognizer:gestureRecognizer];
    
    //时间选择picker
    [self initPickerView];
    
    [self initEnergyAnalysisMenu];
    [self initEnergyQueryMenu];
    [self initShowChartView];
}

-(void)initPickerView{
    _is_picker_show=NO;
    _datePicker=[[MyUIDatePicker alloc]initWithFrame:CGRectMake(0, kScreenH-CommonBarH-kStatusH-[ShiPei CGFloatMakeScale:250], [ShiPei CGFloatMakeScale:860], [ShiPei CGFloatMakeScale:250])];
    [_datePicker setDelegate:self];
    [_pickerOverlay addSubview:_datePicker];
}

-(void)initEnergyAnalysisMenu{
    UIView *EnergyAnalysisMenu=[[UIView alloc]initWithFrame:CGRectMake(0, 0, [ShiPei CGFloatMakeScale:210],  kScreenH-CommonBarH-kStatusH-[ShiPei CGFloatMakeScale:FSCommonBottomH])];
    [_AllBackView addSubview:EnergyAnalysisMenu];
    [EnergyAnalysisMenu setUserInteractionEnabled:YES];
    [EnergyAnalysisMenu setBackgroundColor:[UIColor whiteColor]];
    
    //表格顶部
    UIView *tableTopView=[[UIView alloc]initWithFrame:[ShiPei CGRectMakeScale:10 :15 :185 :35]];
    [EnergyAnalysisMenu addSubview:tableTopView];
    [tableTopView setUserInteractionEnabled:YES];
    [tableTopView setBackgroundColor:FUIColorFromRGB(0x84b6e7)];
    
    UILabel *tableTopLabel=[[UILabel alloc]initWithFrame:[ShiPei CGRectMakeScale:17.5 :0 :130 :35]];
    [tableTopView addSubview:tableTopLabel];
    [tableTopLabel setBackgroundColor:[UIColor clearColor]];
    [tableTopLabel setText:@"贵阳市"];
    [tableTopLabel setTextColor:FUIColorFromRGB(0x333333)];
    [tableTopLabel setFont:[UIFont boldSystemFontOfSize:[ShiPei CGFloatMakeFontScaleWithPX:26]]];
    
    UILabel *tableTopAddLabel=[[UILabel alloc]initWithFrame:[ShiPei CGRectMakeScale:147.5 :0 :37.5 :35]];
    [tableTopView addSubview:tableTopAddLabel];
    [tableTopAddLabel setBackgroundColor:[UIColor clearColor]];
    [tableTopAddLabel setText:@"+"];
    [tableTopAddLabel setTextAlignment:NSTextAlignmentCenter];
    [tableTopAddLabel setTextColor:[UIColor whiteColor]];
    [tableTopAddLabel setFont:[UIFont boldSystemFontOfSize:[ShiPei CGFloatMakeFontScaleWithPX:40]]];
    
    //表格
    _GYMeunTableView=[[UITableView alloc]initWithFrame:CGRectMake([ShiPei CGFloatMakeScale:10], [ShiPei CGFloatMakeScale:50], [ShiPei CGFloatMakeScale:185], kScreenH-CommonBarH-kStatusH-[ShiPei CGFloatMakeScale:FSChangeTrendMenuH+70]-[ShiPei CGFloatMakeScale:FSCommonBottomH])];
    [EnergyAnalysisMenu addSubview:_GYMeunTableView];
    [_GYMeunTableView setBackgroundColor:[UIColor clearColor]];
    [_GYMeunTableView setUserInteractionEnabled:YES];
    [_GYMeunTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_GYMeunTableView setDelegate:self];
    [_GYMeunTableView setDataSource:self];
    
}

-(void)initEnergyQueryMenu{
    _rightAllBackView=[[UIView alloc] initWithFrame:CGRectMake([ShiPei CGFloatMakeScale:225], 0, [ShiPei CGFloatMakeScale:630], kScreenH-CommonBarH-kStatusH)];
    [_AllBackView addSubview:_rightAllBackView];
    [_rightAllBackView setUserInteractionEnabled:YES];
    [_rightAllBackView setBackgroundColor:[UIColor clearColor]];
    
    
    UIView *EnergyQueryMenu=[[UIView alloc]initWithFrame:[ShiPei CGRectMakeScale:0 :15 :630 :40]];
    [_rightAllBackView addSubview:EnergyQueryMenu];
    [EnergyQueryMenu setUserInteractionEnabled:YES];
    [EnergyQueryMenu setBackgroundColor:[UIColor whiteColor]];
    
    UIImageView *ModuleImage=[[UIImageView alloc]initWithFrame:[ShiPei CGRectMakeScale:15 :15 :15 :15]];
    [EnergyQueryMenu addSubview:ModuleImage];
    [ModuleImage setImage:[UIImage imageNamed:@"fs_main_id_image.png"]];
    
    UILabel *ModuleLabel=[[UILabel alloc]initWithFrame:[ShiPei CGRectMakeScale:40 :10 :120 :20]];
    [EnergyQueryMenu addSubview:ModuleLabel];
    [ModuleLabel setText:@"展示"];
    [ModuleLabel setTextColor:FUIColorFromRGB(0x333333)];
    [ModuleLabel setFont:[UIFont boldSystemFontOfSize:[ShiPei CGFloatMakeFontScaleWithPX:28]]];
    
    UILabel *jiangeLabel=[[UILabel alloc]initWithFrame:[ShiPei CGRectMakeScale:400 :0 :50 :40]];
    [EnergyQueryMenu addSubview:jiangeLabel];
    [jiangeLabel setTextAlignment:NSTextAlignmentCenter];
    [jiangeLabel setUserInteractionEnabled:YES];
    [jiangeLabel setText:@"年份"];
    [jiangeLabel setTextColor:FUIColorFromRGB(0x333333)];
    [jiangeLabel setFont:[UIFont boldSystemFontOfSize:[ShiPei CGFloatMakeFontScaleWithPX:25]]];
    
    //年份
    _endTimeMenu=[[UILabel alloc]initWithFrame:[ShiPei CGRectMakeScale:457.5 :7.5 :80 :25]];
    [EnergyQueryMenu addSubview:_endTimeMenu];
    [_endTimeMenu setTextAlignment:NSTextAlignmentCenter];
    [_endTimeMenu setUserInteractionEnabled:YES];
    [_endTimeMenu setBackgroundColor:FUIColorFromRGB(0xe1e1e1)];
    [_endTimeMenu.layer setMasksToBounds:YES];
    [_endTimeMenu.layer setCornerRadius:10];
    [_endTimeMenu setUserInteractionEnabled:YES];
    [_endTimeMenu setText:@""];
    [_endTimeMenu setTextColor:FUIColorFromRGB(0x1b75cc)];
    [_endTimeMenu setFont:[UIFont boldSystemFontOfSize:[ShiPei CGFloatMakeFontScaleWithPX:25]]];
    
    UITapGestureRecognizer *singleTap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectTimeClick:)];
    [_endTimeMenu addGestureRecognizer:singleTap1];
    
    UIButton *queryButton=[[UIButton alloc]initWithFrame:[ShiPei CGRectMakeScale:557.5 :15/2 :50 :25]];
    [EnergyQueryMenu addSubview:queryButton];
    [queryButton setBackgroundImage:[CommonTool createImageWithColor:FUIColorFromRGB(0x3388cb) Frame:[ShiPei CGRectMakeScale:0 :0 :50 :25]] forState:UIControlStateNormal];
    [queryButton setBackgroundImage:[CommonTool createImageWithColor:FUIColorFromRGB(0x639ed7)  Frame:[ShiPei CGRectMakeScale:0 :0 :50 :25]] forState:UIControlStateHighlighted];
    [queryButton.layer setMasksToBounds:YES];
    [queryButton.layer setCornerRadius:5];
    [queryButton setTitle:@"查询" forState:UIControlStateNormal];
    [queryButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [queryButton.titleLabel setFont:[UIFont boldSystemFontOfSize:[ShiPei CGFloatMakeFontScaleWithPX:26]]];
    [queryButton addTarget:self action:@selector(onClickQuery) forControlEvents:UIControlEventTouchUpInside];
}

-(void)initShowChartView{
    _chartAndQueryTableBack=[[UIScrollView alloc]initWithFrame:CGRectMake(0, [ShiPei CGFloatMakeScale:70], [ShiPei CGFloatMakeScale:630], kScreenH-CommonBarH-kStatusH-[ShiPei CGFloatMakeScale:80]-[ShiPei CGFloatMakeScale:FSCommonBottomH])];
    [_rightAllBackView addSubview:_chartAndQueryTableBack];
    [_chartAndQueryTableBack setUserInteractionEnabled:YES];
    _chartAndQueryTableBack.showsVerticalScrollIndicator = FALSE;
    _chartAndQueryTableBack.showsHorizontalScrollIndicator = FALSE;
    _chartAndQueryTableBack.bounces = NO;
    [_chartAndQueryTableBack setBackgroundColor:[UIColor clearColor]];
    
    UIView *showChartBack=[[UIView alloc]initWithFrame:CGRectMake(0, 0, [ShiPei CGFloatMakeScale:630], kScreenH-CommonBarH-kStatusH-[ShiPei CGFloatMakeScale:80]-[ShiPei CGFloatMakeScale:FSCommonBottomH])];
    [_chartAndQueryTableBack addSubview:showChartBack];
    [showChartBack setUserInteractionEnabled:YES];
    [showChartBack setBackgroundColor:[UIColor whiteColor]];
    
    self.chartTitle=[[UILabel alloc]initWithFrame:[ShiPei CGRectMakeScale:10 :0 :600 :30]];
    [self.chartTitle setTextAlignment:NSTextAlignmentCenter];
    [self.chartTitle setText:@""];
    [self.chartTitle setFont:[UIFont boldSystemFontOfSize:[ShiPei CGFloatMakeFontScaleWithPX:20]]];
    [self.chartTitle setTextColor:FUIColorFromRGB(0x333333)];
    [self.chartTitle setBackgroundColor:[UIColor clearColor]];
    [showChartBack addSubview:self.chartTitle];
    
    _bubbleChart=[[BubbleChartView alloc] initWithFrame:CGRectMake(10, 30, 600, 540)];
    _bubbleChart.backgroundColor = [UIColor whiteColor];
    _bubbleChart.delegate = self;
    [showChartBack addSubview:_bubbleChart];
    [self initChartStyleAndData];
}


-(void)onQueren:(MyUIDatePicker *)datePicker{
    //201607（时间格式）
    NSDateFormatter *dateFormat = [ [NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy"];
    NSString *newDateStr = [dateFormat stringFromDate:datePicker.datePicker.date];
    [_endTimeMenu setText:newDateStr];
    _selectTime=newDateStr;
    [_pickerOverlay removeFromSuperview];
    _is_picker_show=NO;
}

-(void)onCancel:(MyUIDatePicker *)datePicker{
    [_pickerOverlay removeFromSuperview];
    _is_picker_show=NO;
}

-(void)overlaycancel{
    [self onCancel:_datePicker];
}

-(void)selectTimeClick:(id)sender{
    if (!_is_picker_show) {
        [self addSubview:_pickerOverlay];
        _is_picker_show=YES;
    }
}

-(void)onClickQuery{
    int i=0;
    if ([_selectTime isEqualToString:@""]) {
        i++;
        [CommonTool showAllTextDialogWithText:@"请选择查询年份" parentView:_AllBackView];
    }
    if (i==0) {
        if([_delegate respondsToSelector:@selector(onQueryChartData:esCode:xslx:selectTime:orgid:area:)]){
            
            [_delegate onQueryChartData:self esCode:@"01" xslx:_xslxType selectTime:_selectTime orgid:_orgId area:_currentAreaName];
        }
    }
}

-(void)setInitCondition{
    //默认显示类型为 jnjpbs=2：类型 1：节能量 2：减排量
    _xslxType=@"1";
    //默认选择贵阳市
    _currentAreaName=@"贵阳市";
    _orgId=@"520100000:4:贵阳市:00";
    //查询时间
    _selectTime=[CommonTool getDateTimeDifferenceWithYear:0 Month:0 Day:0 Rule:@"yyyy"];
    [_endTimeMenu setText:_selectTime];
}

//根据左侧菜单分类填充单选列表
-(void)setGYMenuTableData:(NSArray *)array{
    _conditionInfos=[NSMutableArray array];
    for (int i=1; i<[array count]; i++) {
        NSDictionary *temDic=[array objectAtIndex:i];
        NSString *name=[CommonTool getStringFromNSDictionary:temDic key:@"name" defaultValue:@""];
        NSString *areaId=[CommonTool getStringFromNSDictionary:temDic key:@"id" defaultValue:@""];
        energyConditionInfo *model;
        NSString *encode=[CommonTool getStringFromNSDictionary:temDic key:@"encode" defaultValue:@""];
        if (i%2==0) {
            model=[energyConditionInfo energyConditionInfoWithCondition:name isOdd:@"0" isSelect:@"0" flagNo:
                   areaId encode:encode];
        }else{
            model=[energyConditionInfo energyConditionInfoWithCondition:name isOdd:@"1"  isSelect:@"0" flagNo:
                   areaId encode:encode];
        }
        [_conditionInfos addObject:model];
    }
    //通知主线程刷新
    dispatch_async(dispatch_get_main_queue(), ^{
        //回调或者说是通知主线程刷新
        [self.GYMeunTableView reloadData];
    });
}

#pragma mark - 数据源方法
#pragma mark 返回分组数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

//设置rowHeight
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [ShiPei CGFloatMakeScale:35];
}

#pragma mark 返回每组行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.conditionInfos.count;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    energyConditionInfo *model;
    model=[self.conditionInfos objectAtIndex:indexPath.row];
    _currentAreaName=model.condition;
    //id:name:00
    NSString *temOrgId;
    temOrgId=[@"" stringByAppendingString:model.flagNo];
    temOrgId=[temOrgId stringByAppendingString:@":"];
    temOrgId=[temOrgId stringByAppendingString:model.condition];
    temOrgId=[temOrgId stringByAppendingString:@":"];
    temOrgId=[temOrgId stringByAppendingString:@"00"];
    _orgId=temOrgId;
    if ([_orgId isEqualToString:@""]) {
        _orgId=@"520100000:4:贵阳市:00";
    }
    //执行查询
    [self onClickQuery];
}

#pragma mark返回每行的单元格
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //1.到缓存中去取cell
    static NSString *ID=@"ID";
    //2.没有则创建cell
    areaTableRadioCell *cell=[tableView dequeueReusableCellWithIdentifier:ID];
    if (cell==nil) {
        cell=[[areaTableRadioCell
               alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    //3.设置cell的数据
    cell.areaInfo=self.conditionInfos[indexPath.row];
    //4.返回cell
    return cell;
    
}

-(void)setData{
    if([_delegate respondsToSelector:@selector(onSetData:)]){
        [_delegate onSetData:self];
    }
}

-(void)setBubbleChartData{
    //设置图标题
    [self.chartTitle setText:_title];
    [self setDataCount];
    [_bubbleChart animateWithXAxisDuration:2.0 yAxisDuration:2.0];
}

-(void)initChartStyleAndData{
    [self setupChartView:_bubbleChart];
    [self setChartParam:_bubbleChart];
    [self setLegendStyle:_bubbleChart];
}

#pragma mark - ChartViewDelegate

- (void)chartValueSelected:(ChartViewBase * __nonnull)chartView entry:(ChartDataEntry * __nonnull)entry dataSetIndex:(NSInteger)dataSetIndex highlight:(ChartHighlight * __nonnull)highlight
{
    //    [CommonTool showAllTextDialogWithText:[CommonTool keepDecimal:[NSString stringWithFormat:@"%f",highlight.value]] parentView:self.energyLineChart];
    [CommonTool showAllTextDialogInTopWithText:[CommonTool keepDecimal:[NSString stringWithFormat:@"%f",highlight.value]] parentView:self.bubbleChart];
}

- (void)chartValueNothingSelected:(ChartViewBase * __nonnull)chartView{
    //NSLog(@"chartValueNothingSelected");
}

- (void)setupChartView:(BubbleChartView *)chartView
{
    //描述
    chartView.descriptionText = @"";
    chartView.noDataTextDescription = @"";
    
    chartView.drawGridBackgroundEnabled = NO;
    chartView.dragEnabled = YES;
    [chartView setScaleEnabled:YES];
    chartView.maxVisibleValueCount = 200;
    chartView.pinchZoomEnabled = YES;
}

-(void)setChartParam:(BubbleChartView *)chartView{
    
    chartView.rightAxis.enabled = NO;
    chartView.leftAxis.axisMinValue = 0;//设置Y轴的最小值
    chartView.leftAxis.startAtZeroEnabled = YES;//从0开始绘制
    
    chartView.rightAxis.axisMinValue = 0;//设置Y轴的最小值
    chartView.rightAxis.startAtZeroEnabled = YES;//从0开始绘制
    
    ChartXAxis *xl = chartView.xAxis;
    xl.labelPosition = XAxisLabelPositionBottom;
    xl.labelFont = [UIFont fontWithName:@"HelveticaNeue-Light" size:10.f];
}

//设置图例样式
-(void)setLegendStyle:(BubbleChartView *)chartView{
    ChartLegend *l = chartView.legend;
    l.position = ChartLegendPositionBelowChartCenter;
    l.font = [UIFont fontWithName:@"HelveticaNeue-Light" size:10.f];
}

-(void)setDataCount{
    BubbleChartData *data = [[BubbleChartData alloc] initWithXVals:_xValsBubble dataSets:_yValsBubble];
    [data setValueFont:[UIFont fontWithName:@"HelveticaNeue-Light" size:10.f]];
    [data setHighlightCircleWidth: 1.5];
    [data setValueTextColor:UIColor.whiteColor];
    _bubbleChart.data = data;
}


@end
